package com.yang.framework.common.response;

import com.yang.framework.common.exception.IBaseException;
import com.yang.framework.common.exception.biz.BizException;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class R extends HashMap<String, Object> implements Serializable {
    /**
     * 标志响应是否成功的字段
     */
    private final static String SUCCESS_FIELD = "success";
    /**
     * 数据字段
     */
    private final static String DATA_FIELD = "data";
    /**
     * 提示信息字段
     */
    private final static String MESSAGE_FIELD = "message";
    /**
     * 错误码字段
     */
    private final static String ERROR_CODE_FIELD = "errorCode";

    /**
     *  重写put方法，方便链式调用
     */
    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    /**
     * 处理成功
     */
    public static  R success() {
        return new R().put(SUCCESS_FIELD, true);
    }

    public static R success(Object data) {
        return success().put(DATA_FIELD, data);
    }

    /**
     * 处理失败
     */
    public static R fail(String errorMessage) {
        return new R().put(SUCCESS_FIELD, false)
                      .put(MESSAGE_FIELD, errorMessage);
    }

    public static R fail(String errorCode, String errorMessage) {
        return fail(errorMessage).put(ERROR_CODE_FIELD, errorCode);
    }

    public static R fail(BizException bizException) {
        return fail(bizException.getErrorCode(), bizException.getErrorMessage());
    }

    public static R fail(IBaseException baseException) {
        return fail(baseException.getErrorCode(), baseException.getErrorMessage());
    }

}
